//
//  QYRequestData.swift
//  InsuranceDemo
//
//  Created by liuqingyuan on 2019/12/2.
//  Copyright © 2019 qykj. All rights reserved.
//

import UIKit
import Alamofire
class UploadFileModel {
    var fileName:String?
    var filePath:String?
    var fileData:Data?
    var fileMimeType:String?

    required init() {

    }
}

private let NetWorkRequestShareInstance = QYRequestData()

class QYRequestData{
    class var shared:QYRequestData {
        NetWorkRequestShareInstance
    }
}
//网络请求类型
enum requestMethod {
    case get
    case post
}
//文件上传方式
enum uploadFileType {
    case filePath
    case fileData
}

extension QYRequestData{
    // 网络请求
    // TODO:文件下载
    func downloadFile(urlStr:String,savePath:String,downloadProgress:@escaping (_ progress:Progress)->(),success:@escaping ()->(),failure:@escaping (_ error:Error)->()){
        let downloadUrl = urlStr
        let destination: DownloadRequest.Destination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")
            let saveUrl = URL.init(fileURLWithPath: savePath)
            return (saveUrl, [.removePreviousFile, .createIntermediateDirectories])
        }
        var header:HTTPHeaders = HTTPHeaders()
        if urlStr.contains("l3n") {
            header = HTTPHeaders(arrayLiteral: HTTPHeader(name: "Referer", value: "https://lensdump.com"))
        }
        AF.download(downloadUrl,headers: header, to: destination).downloadProgress { progress in
            downloadProgress(progress)
        }.response { downloadResponse in
            switch downloadResponse.result{
            case .success:
                success()
            case .failure(let error):
                if error.localizedDescription != "Request explicitly cancelled."{
                    failure(error)
                }
            }
        }
    }
    
    // 获取页面html内容
    func getHtmlContent(urlStr:String,method:HTTPMethod,params:[String:String]?,success:@escaping(_ html:String)->(),failure:@escaping(_ error:Error)->()){
        let config = URLSessionConfiguration.af.default;
        config.httpAdditionalHeaders = ["User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"];
        AF.request(urlStr, method: method, parameters: params).responseData { (response) in
            switch response.result{
            case .success(let result):
                let htmlStr = String.init(data: result, encoding: .utf8)
                success(htmlStr!)
            case .failure(let error):
                failure(error)
            }
        }
    }
}
